package com.heima.gateway.filter;

import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取了request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //url是否包含 /login
        String path = request.getURI().getPath();

        if(path.contains("/login")){
            //特殊情况：当前的操作是登录时执行放行
           return chain.filter(exchange);
        }
        //1、判断是否有token，如果没有token返回一个401
        //从请求头中获取token
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isBlank(token)){
        //如果没有token返回一个401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //2、判断token是否合法 （1.token是否为伪造的  2.这个token是否过期）

        try {
            Claims claims = AppJwtUtil.getClaimsBody(token);

            int type = AppJwtUtil.verifyToken(claims);//Claims claims  -1：有效，0：有效，1：过期，2：过期
        //如果type是-1或0代表token有效
            if(type==-1||type==0){
     //        3、解析token中的userId和name，放到请求头中，继续访问微服务
                Integer userId = claims.get("userId", Integer.class);
                String name = claims.get("name", String.class);
    //            放到请求头中
                request.mutate().header("userId",userId.toString());
                request.mutate().header("name",name);

                return chain.filter(exchange);
            }
        } catch (Exception e) {

        }
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;  //越小越先执行
    }
}
